package cn.itsource.user.controller;

import cn.itsource.user.domain.User;
import cn.itsource.user.domain.vo.UserVo;
import cn.itsource.user.service.IUserService;
import cn.itsource.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /*
        code	"123546"
        password	"123"
        passwordRepeat	"123"
        phone	"15008495702"
     */

    @PostMapping("/register")
    public AjaxResult register(@RequestBody UserVo userVo){
        //保存数据
        try {
            userService.registerUser(userVo);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }
    @PostMapping("/login")
    public AjaxResult login(@RequestBody User user){
        //保存数据
        try {
            //获取当当前的登录用户
            User login = userService.login(user);
            //生成一个token 当前的登录用户组合一对数据
            //token 要求：唯一性  
            String token = UUID.randomUUID().toString();
            //存储在redis里面
            redisTemplate.opsForValue().set(token, login, 30, TimeUnit.MINUTES);

            Map<String,Object> map = new HashMap<>();
            map.put("token", token);
            //清除数据里面的敏感数据
            login.setSalt("");
            login.setPassword("");
            login.setState(null);
            map.put("user", login);
            //返回token数据 返回当前的额登录用户
            return AjaxResult.me().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }
}
